"""
@Author    : ghenyar
@Time      : 2025/8/28 16:11
@File      : security.py
@Desc      : 权限认证与授权
"""
from fastapi import Security, HTTPException
from fastapi.security import OAuth2PasswordBearer, SecurityScopes

from app.utils.jwt import JWTUtils
from app.utils.redisCache import RedisCache

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")


async def authority(security_scopes: SecurityScopes, token: str = Security(oauth2_scheme)):
    # 根据令牌获取管理员id
    admin = JWTUtils.decode_token(token)
    # 根据管理员id从redis中获取当前管理员权限
    key = f"login_{admin.get("id")}"
    authorities = await RedisCache.get(key=key)
    if not authorities:
        raise HTTPException(status_code=403, detail="无权限操作、请联系管理员！")
    if isinstance(authorities, dict):
        auth_list = authorities["authorities"]
    else:
        import ast
        authorities = ast.literal_eval(authorities)
        auth_list = authorities["authorities"]
    scope = security_scopes.scopes[0]
    # 鉴权
    if scope not in auth_list:
        raise HTTPException(status_code=403, detail="无权限操作、请联系管理员！")